/**
 * 基础页面类，首页及所有自建页面继承此类
 */
var app = getApp();
var MPage = require('./MPage.js');
var util = require('../utils/util.js');
var ajax = require('../utils/ajax.js');
var common = require('../utils/common.js');
var search = require('../components/search/search.js');
var MCase = require('../components/mCase/mCase.js');
var nearShop = require('../components/nearShop/nearShop.js');
var nearShopList = require('../components/nearShopList/index.js');
var seckillList = require('../components/seckillList/index.js');
var WaiterList = require('../components/waiterList/waiterList.js');
var GoodsList = require('../components/goodsList/goodsList.js');
var ArtList = require('../components/artList/artList.js');
var groupBuy = require('../components/groupBuy/index.js');
var CutList = require('../components/cutList/index.js');
var MUeditor = require('../components/mUeditor/index.js');
var agentSearch = require('../components/agentSearch/index.js');
var CateList = require('../components/cateList/index.js');

const CmptList = [WaiterList, GoodsList, ArtList, CutList, MUeditor, MCase, CateList];

module.exports = common.extendPage(MPage, {

	data: {
		winHei: 0,
		winwid: 0,
		$shop: app.getShop(),
	},

	onShareAppMessage: function() {
		var shop = app.getShop();
		var {
			shareTitle,
			imageUrl,
			type,
			id: pageId,
		} = this.$cPageData;
		var path = "pages/mall/mall?recommend=" + app.getUserId(); //默认首页

		if (type && type != 0) { //自定义页面
			let tabBar = app.config.tabBar;
			var findTabName;

			if (tabBar) {
				Object.keys(tabBar).some(function(key) {
					let pId = tabBar[key];
					if (pId == pageId) {
						findTabName = key;
						return true;
					}
				});
			}
			if (findTabName) { //底部导航自定义页面
				path = 'pages/' + findTabName + "/index?recommend=" + app.getUserId();
			} else {
				path = "pages/mPage1/index?recommend=" + app.getUserId() + '&pageId=' + pageId;
			}
		}

		return {
			title: shareTitle || (shop ? shop.shareTitle : ''),
			imageUrl,
			path,
		}
	},

	onReachBottom(evt) {
		nearShopList.onReachBottom(evt);
	},

	initMPage(pageId, cb) {
		var _self = this;

		search.init({
			page: _self
		});

		agentSearch.init({
			page: _self
		})

		_self._modMapping = app.config.modMapping;

		var dataObj = {
			winHei: app.getWinHei()
		};

		_self._getPageJson(pageId, function(res) {
			var data = res.result['info'] || res.result;
			var pageJson, pModules, page;
			var nearShopMod, hasSeckill, hasGroup, hasNSList;

			pageJson = JSON.parse(data['settings']);
			_self._filterData(pageJson); //转换pageJson style

			page = pageJson.page;
			pModules = pageJson.pModules;

			if (page.dataset) {
				page.dataset['type'] = data.page_type; //重置type，修复老版本后台没有设置type的bug
			}
			_self.$cPageData = page.dataset;

			pModules.forEach(function(mod, modIndex) {
				if (mod.name === 'wxParse') {
					WxParse.wxParse('wxParseArticle', 'html', mod.content.html, _self, 0);
				} else if (mod.name == 'nearShop') {
					nearShopMod = mod;
				} else if (mod.name == 'seckillList') {
					hasSeckill = true;
				} else if (mod.name == 'groupBuy') {
					hasGroup = true;
				} else if (mod.name == 'nearShopList') {
					hasNSList = true;
				} else {
					CmptList.some(function(Cmpt) {
						if (Cmpt.props && Cmpt.props.name == mod.name) {
							let key = '__' + mod.name + '_' + modIndex;
							let scopeKey = '$' + mod.name + modIndex;
							let instance = _self[key];

							mod.scopeKey = scopeKey;
							if (instance) {
								instance.init();
							} else {
								_self[key] = new Cmpt({
									page: _self,
									scope: scopeKey,
									cmpt: mod,
								});
							}
							return true;
						}
					});
				}
			});

			if (nearShopMod) {
				nearShop.init({
					page: _self,
					cmpt: nearShopMod,
				});
			}
			if (hasNSList) {
				nearShopList.init({
					page: _self
				});
			}
			if (hasSeckill) {
				seckillList.init({
					page: _self
				});
			}
			if (hasGroup) {
				groupBuy.init({
					page: _self
				});
			}

			dataObj.pageJson = pageJson;

			if (page.dataset && page.dataset.title) {
				wx.setNavigationBarTitle({
					title: page.dataset.title
				});
			}

			cb(dataObj);
		});
	},

	loginSuc() {
		this.$loginSuc();
	},

	delayLoad() {
		this._parseVideoUrls();

		let techList = app.globalData.techList;

		if (techList) {
			this.setData({
				techList
			});
		}
	},

	//解析视频地址
	_parseVideoUrls() {
		var _self = this;
		var {
			pageJson
		} = _self.data;
		var pModules = pageJson.pModules;

		if (!pModules) {
			return;
		}
		pModules.forEach(function(mod) {
			if (mod['content'].type == 5) { //视频
				var videoUrl = mod['content']['dataset']['url'];

				if (!videoUrl) {
					return;
				}

				ajax.G('/openapi/CHome/parseTxVideoUrl', {
					video_url: videoUrl
				}, function(res) {
					var result = res.result;

					mod['content']['dataset']['url'] = result.url;

					_self.setData({
						pageJson
					});
				})
			}
		});
	},

	goToPage(evt) {
		var pageId = evt.currentTarget.dataset.pageId;
		common.goToPage(pageId);
	},

	goBackPage() {
		common.goBackPage();
	},

	_getPageJson(pageId, cb) {
		var _self = this;
		var ajaxUrl = '/openapi/CPages/getHome';
		var ajaxParams = {
			state: 1
		};

		if (pageId) {
			ajaxUrl = '/openapi/CPages/getPageInfo';
			ajaxParams.pageId = pageId;
		}

		ajax.G(ajaxUrl, ajaxParams, cb);
	},

	//视频详情页
	_toVideo(evt) {
		var {
			needLogin,
			videoId
		} = evt.currentTarget.dataset;
		var {
			isLogin
		} = this.data;

		if (needLogin == 1 && !isLogin) {
			util.alert('视频需要登录才可以查看', function() {
				wx.navigateTo({
					url: '/pages/login/login'
				});
			});
		} else {
			wx.navigateTo({
				url: '/pages/video/video?videoId=' + videoId
			});
		}
	},

	//预览图片
	_previewImg: function(evt) {
		var formId = evt.detail.formId;
		wx.previewImage({
			urls: [evt.currentTarget.dataset.url],
		})
		common.submitForm(formId);
	},

	//转换pageJson数据
	_filterData(pageJson) {
		var {
			page,
			pModules
		} = pageJson;
		var _self = this;

		if (page.style && typeof page.style == 'object') {
			page.style = _self._stringifyStyle(page.style);
		}

		if (pModules) {
			pModules.forEach(function(mod) {
				var content = mod.content;

				//转换style
				if (content && typeof content == 'object') {
					Object.keys(content).forEach(function(key) {
						if (!/(s|S)tyle$/.test(key)) {
							return;
						}
						var styleObj = content[key];

						content[key] = _self._stringifyStyle(styleObj);
						content['o' + key.replace(key.charAt(0), key.charAt(0).toUpperCase())] = styleObj;
					});
				}

				mod['name'] = _self._modMapping[mod['content']['type']];
			});
		}

		return pageJson;
	},

	//styleObj转style string
	_stringifyStyle(styleObj) {
		var styleStr = '';

		function getStyleName(name) {
			return name.replace(/([A-Z])/g, "-$1").toLowerCase();
		}

		if (!styleObj) {
			return styleStr;
		}

		Object.keys(styleObj).forEach(function(key) {
			var val = styleObj[key];
			var valArr = val.trim().match(/(\d+)(px)/);

			key = getStyleName(key);

			if (/\d+px/.test(val)) { //像素值
				val = val.replace(/(\d+)px/g, function(all, num) {
					return num * 2 + (num == 0 ? '' : 'rpx');
				});
			}

			styleStr += key + ':' + val + ';';
		});

		return styleStr;
	}
});